<?php

namespace backend\modules\supplier\models;

use Yii;
use common\models\product\ProductStockLog;

/**
 * 这个模型基于表 "{{%s_storage_in_master}}" 生成。
 *
 * @property integer $id
 * @property string $sn
 * @property string $total_price
 * @property integer $add_id
 * @property integer $add_time
 * @property integer $status
 * @property integer $chk_id
 * @property integer $chk_time
 * @property string $relate_id
 * @property integer $relate_type
 * @property string $remark
 * @property integer $supplier_id
 */
class StorageIn extends \common\models\AR {

    public $modelName = '入库单';

    /**
     * 已审核
     */
    const STATUS_AUDITED = 1;
    /**
     * 未审核
     */
    const STATUS_UNAUDIT = 0;
    const RELATE_TYPE_PURCHASE = 1; //采购进货
    const RELATE_TYPE_ORDER_BACK = 2; //销售退货

//purchase
    /**
     * @inheritdoc
     */

    public static function tableName() {
        return '{{%s_storage_in}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['sn', 'add_id', 'add_time', 'supplier_id'], 'required'],
            [['total_price'], 'number'],
            [['add_id', 'add_time', 'status', 'chk_id', 'chk_time', 'relate_type', 'supplier_id'], 'integer'],
            [['sn'], 'string', 'max' => 15],
            [['relate_id'], 'string', 'max' => 20],
            [['remark'], 'string', 'max' => 50],
            [['sn'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'sn' => '编号',
            'total_price' => '总价',
            'add_id' => '添加人',
            'add_time' => '添加时间',
            'status' => '状态',
            'chk_id' => '审核人',
            'chk_time' => '审核时间',
            'relate_id' => '关联业务单号ID',
            'relate_type' => '关联业务类型：101采购进货，102销售退货',
            'remark' => '备注',
            'supplier_id' => '供应商ID',
        ];
    }

    public function beforeSave($insert) {
        if (!parent::beforeSave($insert)) {
            return FALSE;
        }
        if ($this->isNewRecord) {
            $this->supplier_id = Yii::$app->user->identity->supplier_id;
            $this->add_time = time();
            $this->add_id = Yii::$app->user->identity->id;

            $this->sn = $this->createSn();
        }

        return true;
    }

    public function getDetail() {
        return $this->hasMany(StorageInDetail::className(), ['master_id' => 'id']);
    }

    public function createSn() {
        $supplierId = Yii::$app->user->identity->supplier_id;
        $last = StorageIn::find()->where(['supplier_id' => $supplierId])->orderBy(['id' => SORT_DESC])->one();

        $con = '-';
        $date = date('Ymd');
        if ($last) {
            $arr = explode($con, $last->sn);
            $num = $date == $arr[1] ? intval($arr[2]) + 1 : 1;
        } else {
            $num = 1;
        }
        
        $sn = 'RKD' . $con . $date . $con . str_pad($num, 3, '0', STR_PAD_LEFT);
        
        while (StorageIn::find()->where(['supplier_id' => $supplierId,'sn'=>$sn])->count()!=0){
            return $this->createSn();
        }
        
        return $sn;
    }

    /**
     * 审核入库单
     * @return boolean 审核是否成功
     */
    public function audit() {
        if ($this->status == self::STATUS_AUDITED) {
            return false;
        }

        if ($this->supplier_id != Yii::$app->user->identity->supplier_id) {
            return false;
        }

        $this->status = self::STATUS_AUDITED;
        $this->chk_id = Yii::$app->user->identity->id;
        $this->chk_time = time();
        if ($this->save()) {
            //更货品库存
            foreach ($this->detail as $item) {
                $log = new ProductStockLog;
                $log->type = ProductStockLog::TYPE_PURCHASE_IN;

                $item->product->updateStock($log);
            }

            return true;
        } else {
            return false;
        }
    }

}
